<?php

namespace App\Services\Pay;

use Illuminate\Support\Facades\Log;

class StarsPay
{
    private $merchant_no = "070538";   //商户号 business number
    private $merchant_key = "1af6fca4a5fbde1ccbbdc17ece26e263";  //商户秘钥 Merchant key
    private $api_domain = "https://api.stars-pay.com";  //API域名 API domain name(https://api.xxx.com)

    //1、入金接口 Deposit interface
    public function pay($order)
    {
        Log::channel("debug")->debug("pay:" . json_encode($order));
        $res['code'] = false;
        try {
            $merchant_ref = $order['order_sn'];
            $amount = $order['order_amount'];
            $fiat_currency = $order['fiat_currency'] ?? null;
            $product = $order['jump_product'] ?? "USDT-ERC20Deposit";//产品名称 product name ThaiQR	THB	泰国二维码   ThaiP2P	THB	泰国转账 ...

            //业务请求参数 Business request parameters
            $params = array(
                'merchant_ref' => $merchant_ref,//是	string	商户订单号 Merchant order number
                'product' => $product,//	是	string	产品名称 根据商户后台开通为主 product name Mainly based on the merchant backstage activation
                'amount' => $amount,//	是	string	金额，单位，保留 2 位小数 Amount, unit, 2 decimal places
                //'extra'           => $extra,//	否	Object	额外参数， 默认为json字符串 {} Extra parameters, the default is json string {}
                //'language'        => '',//	否	string	收银台语言选择（详细请看语言代码） Cashier language selection (please see language code for details)
            );


            //extra 参数, 可选字段 extra parameter, optional field
            $extra = array(
                //	否	string	玩家付款账号【需同时传递 bank_code 字段】 Player payment account [need to pass the bank_code field]
                //'account_no' => '1234567890',

                //	否	string	玩家付款银行代码（详细请看银行代码）【需同时传递 account_no 字段】
                //Player's payment bank code (please see bank code for details) [need to pass the account_no field at the same time]
                //'bank_code' => 'KBANK',
            );
            $fiat_currency && $extra['fiat_currency'] = $fiat_currency;

            //判断 额外参数是否为空 Determine whether the extra parameter is empty
            if ($extra) {
                $params['extra'] = $extra;
            }

            //转换json串 Convert json string
            $params_json = json_encode($params, 320);

            //请求参数 Request parameter
            $data = array(
                'merchant_no' => $this->merchant_no,//	是	string	商户号 business number
                'timestamp' => time(),//	是	integer	发送请求的 10 位时间戳 10-bit timestamp of sending request
                'sign_type' => 'MD5',//	是	string	默认为 MD5 Default is MD5
                'params' => $params_json,//	是	string	请求业务参数组成的 JSON String；若接口对应的业务参数不需要字段传输，该字段的值可为空字符串
            );

            $data['sign'] = $this->get_sign($data, $this->merchant_key);//MD5签名 不区分大小写
            $payurl = $this->api_domain . '/api/gateway/pay';//API请求接口地址 API request interface address
            $response = $this->http($payurl, 'POST', $data);//post参数提交，获取数据处理 Post parameter submission, get data processing
            $result = json_decode($response, true);//转换为数组 Convert to array


            $code = isset($result['code']) ? $result['code'] : 404;
            $message = isset($result['message']) ? $result['message'] : 'errorMsg:' . (string)$response;
            if ($code == 200) {
                //下单成功，跳转支付链接 The order is successfully placed, jump to the payment link
                $params = json_decode($result['params'], true);
                $payurl = isset($params['payurl']) ? $params['payurl'] : '';//支付链接 Payment link
                $res['code'] = true;
                $res['url'] = $payurl;
                $res['params'] = $params;

                //使用二维码 Use QR code
//            include 'phpqrcode/phpqrcode.php';
//            $qrcode = isset($params['qrcode']) ? $params['qrcode'] : '';
//            QRcode::png($qrcode, 'qrimg.png');
//            $html = '<img src="qrimg.png" style="width:200px;height:200px;"><br/><p>扫码支付</p>';//Scan code to pay
//            exit($html);

            } else {
                Log::error("pay:" . $message);
            }

        } catch (\Exception $e) {
            Log::error("pay:" . $e->getFile() . "(" . $e->getLine() . ")" . $e->getMessage());
        }

        return $res;
    }


    //1.1、入金接口 异步回调处理 Deposit interface asynchronous callback processing
    public function notify($request)
    {
        //params的参数
        //merchant_ref	是	string	商户订单号
        //system_ref	是	string	平台订单号
        //amount	是	string	金额
        //pay_amount	是	string	实际支付金额
        //fee	是	string	手续费
        //status	是	integer	订单状态：0：Unpaid；1：Paid
        //success_time	是	integer	成功支付时间（时间戳）

        $mysign = $this->get_sign($request, $this->merchant_key); //生成签名 Generate signature
        $params = isset($request['params']) ? json_decode($request['params'], true) : array();
        $sign = isset($request['sign']) ? $request['sign'] : '';

        if ($sign == $mysign) { //验签 Verify signature
            //订单状态，0：待支付，1：支付成功 Order status, 0: Unpaid, 1: paid
            $status = isset($params['status']) ? (int)$params['status'] : 0;
            if ($status == 1) {
                return ['order_code' => $params['merchant_ref'] ?? '', "response" => "SUCCESS"];
            } else {
                $text = "FAIL"; //处理失败 Processing failed
            }
        } else {
            $text = "SIGN_ERROR"; //签名失败 Signature failed
        }
        exit($text);
    }


    //1.2、入金接口 同步回调处理 Deposit interface, synchronous callback processing
    public function return_url()
    {
        //params的参数
        //merchant_ref	是	string	商户订单号
        //system_ref	是	string	平台订单号
        //amount	是	string	金额
        //fee	是	string	手续费
        //status	是	integer	入金订单状态：0：Unpaid；1：Paid
        //success_time	是	integer	成功支付时间（时间戳）

        $request = $_GET;//GET parameters
        $mysign = $this->get_sign($request, $this->merchant_key); //生成签名 Generate signature

        $params = isset($request['params']) ? json_decode($request['params'], true) : array();
        $sign = isset($request['sign']) ? $request['sign'] : '';

        if ($sign != $mysign) { //验签 Verify signature
            //订单状态，0：待支付，1：支付成功 Order status, 0: Unpaid, 1: paid
            $status = isset($params['status']) ? (int)$params['status'] : 0;
            if ($status == 1) {
                //展示成功页面 Show success page
                $text = 'pay success';
            } else {
                //展示处理失败页面 Display the failed page
                $text = 'pay fail';
            }
        } else {
            //展示错误信息页面 签名失败 Display error message page Signing failed
            $text = 'sign_error';
        }
        exit($text);
    }


    //2、出金接口 Withdrawal interface
    public function payout()
    {
        //需要在商户后台配置 IP 白名单 Need to configure the IP whitelist in the merchant background
        $merchant_ref = "O" . date('YmdHis') . rand(10000, 99999);
        $amount = "0.01";
        $product = "ThaiPayout";

        //业务请求参数 Business request parameters
        $params = array(
            'merchant_ref' => $merchant_ref,//	是	string	商户订单号 Merchant order number
            'product' => $product,//	是	integer	产品名称 根据商户后台开通为主 product name Mainly based on the merchant backstage activation
            'amount' => $amount,//	是	string	金额，单位，保留 2 位小数 Amount, unit, 2 decimal places
        );

        //extra 参数, 可选字段 extra parameter, optional field
        $extra = array(
            'account_name' => 'zhangsan',//	是	string	持卡人姓名 Cardholder's Name
            'account_no' => '1122334455',//	是	string	银行卡号 Bank card number
            'bank_code' => 'KBANK',//	是	string	提现银行代码 Withdrawal bank code or IFSC or UPI
        );

        //判断 额外参数是否为空 Determine whether the extra parameter is empty
        if ($extra) {
            $params['extra'] = $extra;
        }

        //转换json串 Convert json string
        $params_json = json_encode($params, 320);

        //请求参数 Request parameter
        $data = array(
            'merchant_no' => $this->merchant_no,//	是	string	商户号 business number
            'timestamp' => time(),//	是	integer	发送请求的 10 位时间戳 10-bit timestamp of sending request
            'sign_type' => 'MD5',//	是	string	默认为 MD5 Default is MD5
            'params' => $params_json,//	是	string	请求业务参数组成的 JSON String；若接口对应的业务参数不需要字段传输，该字段的值可为空字符串
        );

        $data['sign'] = $this->get_sign($data, $this->merchant_key);//MD5签名 不区分大小写 MD5 signature is not case sensitive

        $payurl = $this->api_domain . '/api/gateway/withdraw';//API接口地址 API interface address
        $response = $this->http($payurl, 'POST', $data);//post参数提交，获取数据处理 Post parameter submission, get data processing
        $result = json_decode($response, true);//转换为数组 Convert to array

        $code = isset($result['code']) ? $result['code'] : 404;
        $message = isset($result['message']) ? $result['message'] : 'errorMsg:' . (string)$response;
        if ($code == 200) {
            $params = json_decode($result['params'], true);
            //订单状态：1：Success； 2: Pending；5: Reject
            $status = isset($params['status']) ? (int)$params['status'] : 0;
            if ($status == 1 || $status == 2) {
                exit('代付提交成功');//Submitted successfully
            } elseif ($status == 5) {
                exit('代付提交失败' . $message);//Failed to submit payment
            } else {
                exit('代付提交其他错误' . $message);//Submit other errors
            }
        } else {
            exit('下单失败，返回错误信息：' . $message);//The order fails and an error message is returned
        }
    }


    //2.1、出金出金接口 异步回调处理 Asynchronous callback processing
    public function payout_notify()
    {
        //params的参数
        //merchant_ref	string	商户订单号
        //system_ref	string	平台订单号
        //amount	string	金额
        //fee	string	手续费
        //status	integer	订单状态：1：Success； 2: Pending；5: Reject
        //success_time	integer	成功支付时间（时间戳）

        $request = $_POST; //POST参数 POST parameters
        $mysign = $this->get_sign($request, $this->merchant_key); //生成签名 Generate signature

        $params = isset($request['params']) ? json_decode($request['params'], true) : array();
        $sign = isset($request['sign']) ? $request['sign'] : '';

        if ($sign == $mysign) { //验签 Verify signature
            //订单状态，1：支付，2：待定，3：失败 Order status, 1: Success, 2: Pending, 5: Reject
            $status = isset($params['status']) ? (int)$params['status'] : 0;
            if ($status == 1) {
                //处理订单成功的逻辑 The logic of processing the order successfully
                //....
                //....
                $text = "SUCCESS"; //处理成功,返回的标识 The processing is successful, the returned ID
            } elseif ($status == 5) {
                //处理失败逻辑 Handling failure logic
                //...
                //...
                $text = "Reject"; //处理失败 Processing failed
            } else {
                $text = "Pending"; //处理失败 Processing failed
            }
        } else {
            $text = "SIGN_ERROR"; //签名失败 Signature failed
        }
        exit($text);
    }


    //3、查询商户余额 Check merchant balance
    public function query_balance()
    {
        //需要在商户后台配置 IP 白名单 Need to configure the IP whitelist in the merchant backgroun
        //业务请求参数 Business request parameters
        $params = array(
            "currency" => 'THB', //	是	货币类型 Currency type
        );

        //转换json串 Convert json string
        $params_json = json_encode($params, 320);

        //请求参数 Request parameter
        $data = array(
            'merchant_no' => $this->merchant_no,//	是	string	商户号 business number
            'timestamp' => time(),//	是	integer	发送请求的 10 位时间戳 10-bit timestamp of sending request
            'sign_type' => 'MD5',//	是	string	默认为 MD5 Default is MD5
            'params' => $params_json,//	是	string	请求业务参数组成的 JSON String；若接口对应的业务参数不需要字段传输，该字段的值可为空字符串
        );

        $data['sign'] = $this->get_sign($data, $this->merchant_key);//MD5签名 不区分大小写 MD5 signature is not case sensitive

        $payurl = $this->api_domain . '/api/gateway/query/balance';//API请求接口地址 API request interface address
        $response = $this->http($payurl, 'POST', $data);//post参数提交，获取数据处理 Post parameter submission, get data processing
        $result = json_decode($response, true);//转换为数组 Convert to array

        $code = isset($result['code']) ? $result['code'] : 404;
        $message = isset($result['message']) ? $result['message'] : 'errorMsg:' . (string)$response;
        if ($code == 200) {
            //current_balance	string	当前余额
            //available_balance	string	可用余额
            //pending_settlement	string	在途结算
            //pending_payout	string	在途代付

            $params = isset($result['params']) ? json_decode($result['params'], true) : array();

            $current_balance = isset($params['current_balance']) ? $params['current_balance'] : 0;
            $available_balance = isset($params['available_balance']) ? $params['available_balance'] : 0;
            $pending_settlement = isset($params['pending_settlement']) ? $params['pending_settlement'] : 0;
            $pending_payout = isset($params['pending_payout']) ? $params['pending_payout'] : 0;

            echo "当前余额:" . $current_balance . "，可用余额:" . $available_balance . "，在途结算:" . $pending_settlement . "，在途代付:" . $pending_payout;
            exit;
        } else {
            exit('查询失败，返回失败信息：' . $message);//Query failed, return failure message
        }
    }


    //4、批量查询订单状态 Batch query order status
    public function query_order()
    {
        //需要在商户后台配置 IP 白名单 Need to configure the IP whitelist in the merchant backgroun
        $merchant_refs = ["Oxxxx1", "Oxxxx2", "Oxxxx3"];

        //业务请求参数 Business request parameters
        $params = array(
            "merchant_refs" => $merchant_refs, //	是	array	商户订单号列表 Merchant order number list
        );

        //转换json串 Convert json string
        $params_json = json_encode($params, 320);

        //请求参数 Request parameter
        $data = array(
            'merchant_no' => $this->merchant_no,//	是	string	商户号 business number
            'timestamp' => time(),//	是	integer	发送请求的 10 位时间戳 10-bit timestamp of sending request
            'sign_type' => 'MD5',//	是	string	默认为 MD5 Default is MD5
            'params' => $params_json,//	是	string	请求业务参数组成的 JSON String；若接口对应的业务参数不需要字段传输，该字段的值可为空字符串
        );

        $data['sign'] = $this->get_sign($data, $this->merchant_key);//MD5签名 不区分大小写 MD5 signature is not case sensitive

        $payurl = $this->api_domain . '/api/gateway/batch-query/order';//API请求接口地址 API request interface address
        $response = $this->http($payurl, 'POST', $data);//post参数提交，获取数据处理 Post parameter submission, get data processing
        $result = json_decode($response, true);//转换为数组 Convert to array

        $code = isset($result['code']) ? $result['code'] : 404;
        $message = isset($result['message']) ? $result['message'] : 'errorMsg:' . (string)$response;
        if ($code == 200) {
            $params = isset($result['params']) ? json_decode($result['params'], true) : array();

            foreach ($params as $key => $value) {
                $order = isset($value['merchant_ref']) ? $value['merchant_ref'] : ''; # 商户订单号 Merchant order number
                $status = isset($value['status']) ? (int)$value['status'] : 0; //订单状态，0：待支付，1：支付 Order status, 0: unpaid, 1: paid
                if ($status == 1) {
                    //处理成功的订单信息 Successfully processed order information
                    echo "成功";
                } else {
                    //未支付 unpaid
                    echo "未处理";
                }
            }

        } else {
            exit('查询失败，返回失败信息：' . $message);//Query failed, return failure message
        }

    }


    //签名 signature
    public function get_sign($data = array(), $key = '')
    {
        //组装签名字段 签名 MD5(merchant_no+params+sign_type+timestamp+Key)-说明key 是商户秘钥
        //Assemble the signature field Signature MD5 (merchant_no+params+sign_type+timestamp+Key)-indicating that the key is the merchant secret key
        $merchant_no = isset($data['merchant_no']) ? $data['merchant_no'] : '';
        $params = isset($data['params']) ? $data['params'] : '';
        $sign_type = isset($data['sign_type']) ? $data['sign_type'] : '';
        $timestamp = isset($data['timestamp']) ? $data['timestamp'] : '';

        $sign_str = $merchant_no . $params . $sign_type . $timestamp . $key;
        $sign = md5($sign_str);//MD5签名 不区分大小写  MD5 signature is not case sensitive
        return $sign;
    }

    //post参数提交,可根据自己情况修改换成别的函数 Post parameter submission, you can modify and replace it with other functions according to your own situation
    public function http($url = '', $method = 'POST', $postData = array(), $header = array())
    {
        $data = '';
        if (!empty($url)) {
            try {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_HEADER, false);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_TIMEOUT, 30); //30秒超时
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名

                if ($header) {
                    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                }

                if (strtoupper($method) == 'POST') {
                    $curlPost = is_array($postData) ? http_build_query($postData) : $postData;
                    curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
                }
                $data = curl_exec($ch);
                curl_close($ch);
            } catch (Exception $e) {
                $data = '';
            }
        }
        return $data;
    }
}


